<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <video id="video" width="300" height="300" controls></video>
  <button id="photo">按钮</button>
  <canvas id="canvas" width="300" height="300"></canvas>
  <script>
    let video = document.getElementById('video')
    let btv = document.getElementById('photo')
    let canvas = document.getElementById('canvas')
    let context = canvas.getContext('2d')


    //访问用户媒体设备的兼容方法
    function init(constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        //最新的标准API
        navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
      } else if (navigator.webkitGetUserMedia) {
        //webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error)
      } else if (navigator.mozGetUserMedia) {
        //firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
        //旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    }
    // function init(constraints, success, error) {
    //不严谨的情况下直接这样写就修改，不用考虑兼容问题
    //     navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error)
    // }

    function success(stream) {
      //兼容webkit核心浏览器
      let CompatibleURL = window.URL || window.webkitURL;
      //将视频流设置为video元素的源
      //video.src = CompatibleURL.createObjectURL(stream);

      video.srcObject = stream;
      video.play();
      console.log('成功')
    };

    function error(error) {
      console.log('失败')
    }
    if (navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
      navigator.getUserMedia) {
      init({
        video: {
          width: 300,
          height: 300
        }
      }, success, error)
    } else {
      alert('不支持访问用户媒体');
    }

    document.getElementById('photo').addEventListener('click', function () {
      context.drawImage(video, 0, 0, 300, 300);
    })
  </script>
</body>

</html>